package com.example.utils;

import java.sql.*;

public class BaseDao {
    private static Connection connection=null;
    private static PreparedStatement preparedStatement=null;
    static{
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/kh63?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true", "root", "123456");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //修改
    public static ResultSet select(String sql, Object[]objects){
        ResultSet resultSet=null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            if(objects!=null){
                    for (int i = 0; i < objects.length; i++) {
                        preparedStatement.setObject(i+1,objects[i]);
                }
            }
             resultSet = preparedStatement.executeQuery();
        } catch (Exception e) {
           e.printStackTrace();
        }
        return resultSet;
    }
    //关闭流
    public static void close(ResultSet resultSet){
        try {
            if(resultSet!=null){
                resultSet.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    //增删改方法
    public static int modify(String sql,Object[]objects){
        int j=-1;
        try {
            preparedStatement = connection.prepareStatement(sql);
            if(objects.length!=0){
                for (int i = 0; i < objects.length; i++) {
                    preparedStatement.setObject(i+1,objects[i]);
                }
            }
           j= preparedStatement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return j;
    }
}
